package com.dalei.vdserver.webservice;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.jws.WebService;

import com.dalei.vdserver.dao.DeviceStatusDao;
import com.dalei.vdserver.dao.UserDao;
import com.dalei.vdserver.model.DeviceStatus;
import com.dalei.vdserver.model.ErrorCode;
import com.dalei.vdserver.model.User;
import com.dalei.vdserver.security.MD5Encryption;
import com.google.gson.Gson;

@WebService(endpointInterface = "com.dalei.vdserver.webservice.LoginService")
public class LoginServiceImpl implements LoginService {

	private UserDao userDao;

	private DeviceStatusDao deviceStatusDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public DeviceStatusDao getDeviceStatusDao() {
		return deviceStatusDao;
	}

	public void setDeviceStatusDao(DeviceStatusDao deviceStatusDao) {
		this.deviceStatusDao = deviceStatusDao;
	}

	@Override
	public String getUsers() {
		// TODO Auto-generated method stub
		List<String> names = new ArrayList<String>();
		List<User> users = userDao.getUsers();
		if (users != null) {
			for (User user : users) {
				names.add(user.getUserName());
			}
		}
		Gson gson = new Gson();
		return gson.toJson(names, List.class);
	}

	@Override
	public int validateUser(String user, String password) {
		// TODO Auto-generated method stub
		User u = userDao.getUserByUserName(user);
		if (u != null) {
			List<DeviceStatus> dss = deviceStatusDao.getStatusOfOnlineDevices();
			for (DeviceStatus ds : dss) {
				if (ds.getCurrentUserId() == u.getId()) {
					return ErrorCode.Login.ALREADY_LOGGED_ON;
				}
			}
			if (u.getPassword() != null) {
				boolean result = false;
				String pwd = null;
				if (password != null) {
					pwd = password;
				} else {
					pwd = "";
				}
				try {
					result = MD5Encryption.validatePassword(pwd,
							u.getPassword());
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return ErrorCode.INTERNAL_ERROR;
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return ErrorCode.INTERNAL_ERROR;
				}
				if (result) {
					return u.getId();
				} else {
					return ErrorCode.Login.INVALID_PASSWORD;
				}
			} else {
				if (password == null || password.equals("")) {
					return u.getId();
				} else {
					return ErrorCode.Login.INVALID_PASSWORD;
				}
			}
		} else {
			return ErrorCode.Login.USER_NOT_FOUND;
		}
	}
}
